package ochart.serialization.json.oChart.elements.axes
{
	import ochart.core.ChartObject;
	import ochart.core.ChartObjectFactory;
	import ochart.elements.axes.AxisBase;
	import ochart.elements.axes.Tick;
	import ochart.elements.labels.Label;
	import ochart.elements.labels.LabelBase;
	import ochart.serialization.json.JSON;
	import ochart.serialization.json.oChart.JSONSerializer;
	
	public class AxisBaseSerializer extends JSONSerializer
	{
		public function AxisBaseSerializer()
		{
			super();
		}
		
		override public function fromJSON(json:Object):Boolean
		{
			if(!super.fromJSON(json))
			{
				return false;
			}
			
			var axisBase:AxisBase = target as AxisBase;
			if(json[Label.ALIAS])
			{
				if(json[Label.ALIAS][AxisBase.VALUES_NAME])
				{
					axisBase.labelValuesArray = json[Label.ALIAS][AxisBase.VALUES_NAME];
				}
				if(axisBase.min == 0 && axisBase.max == 0)
				{
					axisBase.max = axisBase.labelValuesArray.length - 1;
					axisBase.steps = 1;
				}
				
				var label:Label = ChartObjectFactory.instance.create(Label.ALIAS) as Label;
				label.chart = axisBase.chart;
				label.fromData(json[Label.ALIAS]);					
				var labelsArray:Array = [];
				var labelIndex:int = 0;
				while(labelIndex < axisBase.labelCount)
				{
					var cloneLabel:Label = label.clone() as Label;
					var text:* = "";
					if((axisBase.labelValuesArray is Array) && axisBase.labelValuesArray.length > labelIndex)
					{
						text = axisBase.labelValuesArray[labelIndex];
					}
					else
					{
						text = axisBase.min + axisBase.steps * labelIndex;
					}
					if(text == null)
					{
						labelsArray.push(null);
					}
					else
					{
						cloneLabel.text = text;
						labelsArray.push(cloneLabel);
					}
					labelIndex++;
				}
				axisBase.labelsArray = labelsArray;
			}
			
			if(json[Tick.ALIAS])
			{
				var tick:Tick = ChartObjectFactory.instance.create(Tick.ALIAS) as Tick;
				tick.chart = axisBase.chart;
				tick.fromData(json[Tick.ALIAS]);
				var ticksArray:Array = [];
				var tickCount:int = axisBase.tickCount;
				while(tickCount > 0)
				{
					ticksArray.push(tick.clone());
					tickCount--;
				}
				axisBase.ticksArray = ticksArray;
			}
			
			return true;
		}
		
		override public function toJSON():JSON
		{
			var json:JSON = super.toJSON();
			return json;
		}
	}
}